package edu.uwm.universitydb.controller;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;

import edu.uwm.universitydb.view.ProfessorMaint;
import edu.uwm.universitydb.framework.exception.DataAccessException;
import edu.uwm.universitydb.model.Department;
import edu.uwm.universitydb.model.Professor;
import edu.uwm.universitydb.service.ServiceFactory;
import edu.uwm.universitydb.service.professor.ProfessorService;
import edu.uwm.universitydb.swing.ProfessorTableModel;

public class ProfessorMaintController implements MouseListener {
	
	public ProfessorMaintController() {
		_professorService = ServiceFactory.getInstance().getProfessorService();
		// Create our associated view
		_view = new ProfessorMaint(new ProfessorTableModel(_professorService));
		
		// Setup our listeners
		_view.getAddButton().addMouseListener(this);
		_view.getEditButton().addMouseListener(this);
		_view.getDelButton().addMouseListener(this);

	}
	private void onAddButtonClick() {
		//Dummy values
		String ssn= "";
		String name= "";
		int age = -1;
		String rank = "";
		String speciality = "";
		Department dept = null;
		
		//Show Edit User View
		JPanel panel = _view.showNewView();
		boolean validated = false;
		while (!validated) {
			int result = JOptionPane.showConfirmDialog(_view, panel, "Add", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
			if (result == JOptionPane.OK_OPTION) {
				//Get user inputs
				for( Component c : panel.getComponents()) {
					if (ProfessorMaint.SSNFIELD.equals(c.getName())) {
						ssn = ((JTextField)c).getText();
					} else if  (ProfessorMaint.NAMEFIELD.equals(c.getName())) {
						name = ((JTextField)c).getText();
					} else if  (ProfessorMaint.AGEFIELD.equals(c.getName())) {
						age = Integer.parseInt(((JTextField)c).getText());
					} else if  (ProfessorMaint.RANKFIELD.equals(c.getName())) {
						rank = ((JTextField)c).getText();
					} else if  (ProfessorMaint.SPCFIELD.equals(c.getName())) {
						speciality = ((JTextField)c).getText();
					} else if  (ProfessorMaint.DEPTFIELD.equals(c.getName())) {
						dept = ((Department)((JComboBox<Department>)c).getSelectedItem());
					}
				}
				// Add User
				final Professor prof = new Professor(ssn,age, name, rank, speciality, dept);
				boolean status = false;
				try {
					status = _professorService.addProfessor(prof);
				} catch (DataAccessException e) {
					JOptionPane.showMessageDialog(_view,  e.getMessage());
				}
				if (status == false) {
					JOptionPane.showMessageDialog(_view, "Error adding user!");
				} else {
					validated = true;
				}
			} else {
				//User cancelled add
				break;
			}
			_view.refreshTable();
		}
	}
	
	private void onEditButtonClick() {
		JTable dataTable =  _view.getDataTable();
		//A single row needs to be selected
		int numRows = dataTable.getSelectedRowCount();
		if( numRows == 0 || numRows > 1) {
			JOptionPane.showMessageDialog(_view, "Please select a single row to Edit!");
		} else {
			//Get Selected SSN
			String id = (String) dataTable.getValueAt(dataTable.getSelectedRow(), 0);
			Professor prof = _professorService.searchProfessorBySSN(id);
			
			String ssn= prof.getSsnNum();
			String name= prof.getName();
			int age = prof.getAge();
			String rank = prof.getRank();
			String speciality = prof.getResearchSpeciality();
			Department dept = prof.getDepartment();
			
			//Show Edit User View
			JPanel panel = _view.showMaintView(id, name, age, rank, speciality, dept);

			boolean validated = false;
			while (!validated) {
				int result = JOptionPane.showConfirmDialog(_view, panel, "Edit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
				if (result == JOptionPane.OK_OPTION) {
					//Get user inputs
					for( Component c : panel.getComponents()) {
						if (ProfessorMaint.SSNFIELD.equals(c.getName())) {
							ssn = ((JTextField)c).getText();
						} else if  (ProfessorMaint.NAMEFIELD.equals(c.getName())) {
							name = ((JTextField)c).getText();
						} else if  (ProfessorMaint.AGEFIELD.equals(c.getName())) {
							age = Integer.parseInt(((JTextField)c).getText());
						} else if  (ProfessorMaint.RANKFIELD.equals(c.getName())) {
							rank = ((JTextField)c).getText();
						} else if  (ProfessorMaint.SPCFIELD.equals(c.getName())) {
							speciality = ((JTextField)c).getText();
						} else if  (ProfessorMaint.DEPTFIELD.equals(c.getName())) {
							dept = ((Department)((JComboBox<Department>)c).getSelectedItem());
						}
					}
					// Update User
					final Professor editprof = new Professor(ssn,age, name, rank, speciality, dept);
					boolean status = false;
					try {
						status = _professorService.updateProfessor(editprof);
					} catch (DataAccessException e) {
						JOptionPane.showMessageDialog(_view, e.getMessage());
					}
					if (status == false) {
						JOptionPane.showMessageDialog(_view, "Error editing user!");
					} else {
						validated = true;
					}
				} else {
					//User cancelled edit
					break;
				}
				_view.refreshTable();
			}
		}
	}
	
	private void onDelButtonClick() {
		JTable dataTable = _view.getDataTable();
		int numRows = dataTable.getSelectedRowCount();
		
		//At least 1 row needs to be selected
		if (numRows == 0) {
			JOptionPane.showMessageDialog(_view, "Please select row/s to Delete!");
		} else {
			//Confirm delete
			int confirm = JOptionPane.showConfirmDialog(_view,
					"Are you sure you want to delete?", "Confirm", JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION) {
				List<String> selectedKeys = new ArrayList<String>();
				boolean status = true;
				for (int i : dataTable.getSelectedRows()) {
					String keyVal = (String)dataTable.getValueAt(i, 0);
					selectedKeys.add(keyVal);
				}
				//Perform Delete
				for (String key : selectedKeys) {
					status = _professorService.removeProfessor(key);
					if (status == false) {
						JOptionPane.showMessageDialog(_view, "Error deleting user!");
						break;
					}
				}
				dataTable.clearSelection();
				_view.refreshTable();
			}
		}
	}
	
	public ProfessorMaint getView() {
		return _view;
	}
	
	
	@Override
	public void mouseClicked(MouseEvent e) {
		//Based on the element clicked, fire off appropriate handler method.
		switch(e.getComponent().getName()) {
			case ProfessorMaint.EDITBUTTON: 
				this.onEditButtonClick();
				break;
			case ProfessorMaint.DELBUTTON: 
				this.onDelButtonClick();
				break;
			case ProfessorMaint.ADDBUTTON: 
				this.onAddButtonClick();
				break;
			default: 
				//Not sure what they clicked, do nothing
				break;
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// Unused		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// Unused
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// Unused
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// Unused
	}	
	

	private ProfessorMaint _view;
	
	private ProfessorService _professorService;
	
	public static final String ID = "ProfMnt";
}
